/**
 * 
 */
package com.ej.methods;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Return empty arrays or collections, not nulls
 * 
 * There is no reason ever to return null from an array- or collection-valued
 * method instead of returning an empty array or collection
 * 
 * @author Sunaina.Sharma
 * 
 */
public class ReturnEmptyObjectVsNull {

	class Cheese {

	}

	// The right way to return an array from a collection
	private final List<Cheese> cheesesInStock = new ArrayList<Cheese>();
	private static final Cheese[] EMPTY_CHEESE_ARRAY = new Cheese[0];

	/**
	 * @return an array containing all of the cheeses in the shop.
	 */
	public Cheese[] getCheeses() {
		/*
		 * In this idiom, an empty-array constant is passed to the toArray
		 * method to indicate the desired return type. Normally the toArray
		 * method allocates the returned array, but if the collection is empty,
		 * it fits in the zero-length input array, and the specification for
		 * Collection.toArray(T[]) guarantees that the input array will be
		 * returned if it is large enough to hold the collection. Therefore the
		 * idiom never allocates an empty array
		 */
		return cheesesInStock.toArray(EMPTY_CHEESE_ARRAY);
	}

	// The right way to return a copy of a collection
	public List<Cheese> getCheeseList() {
		if (cheesesInStock.isEmpty())
			return Collections.emptyList(); // Always returns same list
		else
			return new ArrayList<Cheese>(cheesesInStock);
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {

	}

}
